unit MAIN;

interface

uses Windows, SysUtils, Classes, Graphics, Forms, Controls, Menus,ShellApi, fileCtrl,
  StdCtrls, Dialogs, Buttons, Messages, ExtCtrls, ComCtrls, StdActns,
  ActnList, ToolWin, ImgList, TPS_Tambah, Unit_External, viewTPS, Setting, TPS_Tambah_Orang, TPS_Pindah,
  TPS_Print, PPS_Tambah, PPS_View, Form_NewData, rekap, sync, viewDPT, dpt_import, Unit7, xView, xxView,
  DB, ZAbstractRODataset, ZAbstractDataset, ZAbstractTable, ZDataset,log_activity,log_sync,crud,
  ZConnection, frxpngimage, jpeg, JvThread, JvThreadDialog, JvComponentBase, BackupKec;

const
  WM_AFTER_SHOW = WM_USER + 300; // custom message

type
  TMyWorkerThread = class(TThread)
  public
    proses_sekarang:integer;
    number:integer;
    session_kode:string;
    procedure Execute; override;
  end;
  TLoginForm = class(TForm)
    Login:TForm;
  end;
  TMainForm = class(TForm)
    ZConnection1: TZConnection;
    MainMenu1: TMainMenu;
    File1: TMenuItem;
    FileNewItem: TMenuItem;
    FileCloseItem: TMenuItem;
    Window1: TMenuItem;
    Help1: TMenuItem;
    ViewDataPemilih: TMenuItem;
    HelpAboutItem: TMenuItem;
    OpenDialog: TOpenDialog;
    StatusBar: TStatusBar;
    ActionList1: TActionList;
    EditCut1: TEditCut;
    EditCopy1: TEditCopy;
    EditPaste1: TEditPaste;
    FileNew1: TAction;
    FileSave1: TAction;
    FileExit1: TAction;
    FileOpen1: TAction;
    FileSaveAs1: TAction;
    WindowCascade1: TWindowCascade;
    WindowTileHorizontal1: TWindowTileHorizontal;
    WindowArrangeAll1: TWindowArrange;
    WindowMinimizeAll1: TWindowMinimizeAll;
    HelpAbout1: TAction;
    FileClose1: TWindowClose;
    WindowTileVertical1: TWindowTileVertical;
    ToolBar2: TToolBar;
    ToolButton8: TToolButton;
    ToolButton10: TToolButton;
    ToolButton11: TToolButton;
    ImageList1: TImageList;
    Action1: TAction;
    Action2: TAction;
    Action3: TAction;
    ToolButton1: TToolButton;
    ToolButton2: TToolButton;
    ToolButton4: TToolButton;
    ToolButton5: TToolButton;
    WindowClose1: TWindowClose;
    Action4: TAction;
    Action5: TAction;
    ToolButton7: TToolButton;
    ToolButton6: TToolButton;
    Action6: TAction;
    Action7: TAction;
    ToolPrint: TToolButton;
    Action8: TAction;
    Action9: TAction;
    Action10: TAction;
    Action11: TAction;
    ToolButtonz: TToolButton;
    PenyusunandanPerbaikanDPT1: TMenuItem;
    Sinkronisasi1: TMenuItem;
    ViewTPS1: TMenuItem;
    ViewDataPemilih1: TMenuItem;
    ViewTPS2: TMenuItem;
    BuatFileSinkronisasi1: TMenuItem;
    ImportFileSinkronisasi1: TMenuItem;
    ImportDPTTerakhir1: TMenuItem;
    ViewDPTTerakhir1: TMenuItem;
    utupProsesDP41: TMenuItem;
    utupProsesDPS1: TMenuItem;
    utupProsesDPTambahan1: TMenuItem;
    utupProsesDPT1: TMenuItem;
    menuInformasi1: TMenuItem;
    EksportPrintFormkPU1: TMenuItem;
    DataMaster1: TMenuItem;
    ProsesLabel: TLabel;
    ZQuery1: TZQuery;
    Logout: TMenuItem;
    Pengaturan1: TMenuItem;
    LogAktivitas1: TMenuItem;
    LogAktivitasPemutakhiranDataPemilih1: TMenuItem;
    LogAktivitasSinkronisasi1: TMenuItem;
    Label2: TLabel;
    Label1: TLabel;
    Image1: TImage;
    Image2: TImage;
    PenyusunanDPS1: TMenuItem;
    utupProsesDPSDPTambahan1: TMenuItem;
    ManajemenTPS1: TMenuItem;
    PemutakhiranDataPemilih1: TMenuItem;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    JvThread2: TJvThread;
    JvThreadSimpleDialog2: TJvThreadSimpleDialog;
    BackupDatabase1: TMenuItem;
    RestoreDatabase1: TMenuItem;
    estDump1: TMenuItem;
    qryCek: TZQuery;
    qryTabel: TZQuery;
    threadUpdate: TJvThread;
    threadDialogUpdate: TJvThreadSimpleDialog;
    Memo1: TMemo;
    ResetSinkronisasi1: TMenuItem;
    Label6: TLabel;
    threadBuatSync: TJvThread;
    threadDialogBuatSync: TJvThreadSimpleDialog;
    procedure ExcelImportExecute(Sender: TObject);
    procedure FileOpen1Execute(Sender: TObject);
    procedure TambahDataPemilihClick(Sender: TObject);
    procedure FileExit1Execute(Sender: TObject);
    procedure printtps(Sender: TObject);
    procedure ToolButton1Click(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure ToolButton4Click(Sender: TObject);
    procedure ToolButton5Click(Sender: TObject);
    procedure ToolButton6Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Fo1Click(Sender: TObject);
    procedure ToolButton7Click(Sender: TObject);
    procedure toolClick(Sender: TObject);
    procedure ToolPrintClick(Sender: TObject);
    procedure pps_formClick(Sender: TObject);
    procedure ToolButtonzClick(Sender: TObject);
    procedure ToolButton3Click(Sender: TObject);
    procedure FileCloseItemClick(Sender: TObject);
    procedure ViewDataPemilihClick(Sender: TObject);
    procedure FormPrintTPS(Sender: TObject);
    procedure FormPetugas1Click(Sender: TObject);
    procedure ViewTPSClick(Sender: TObject);
    procedure BuatFileSinkronisasi1Click(Sender: TObject);
    procedure ImportFileSinkronisasi1Click(Sender: TObject);
    procedure ImportDPTTerakhir1Click(Sender: TObject);
    procedure ViewDPTTerakhir1Click(Sender: TObject);
    procedure DataMaster1Click(Sender: TObject);
    procedure menuInformasi1Click(Sender: TObject);
    procedure ViewDPTPemutakhirClick(Sender: TObject);
    procedure EksportPrintFormkPU1Click(Sender: TObject);
    procedure LogoutClick(Sender: TObject);
    procedure ViewDataPemilihTambClick(Sender: TObject);
    procedure Pengaturan1Click(Sender: TObject);
    procedure LogAktivitas1Click(Sender: TObject);
    procedure LogAktivitasSinkronisasi1Click(Sender: TObject);
    procedure User1Click(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure JvThread2Execute(Sender: TObject; Params: Pointer);
    procedure JvThread2FinishAll(Sender: TObject);
    procedure BackupDatabase1Click(Sender: TObject);
    procedure RestoreDatabase1Click(Sender: TObject);
    procedure estDump1Click(Sender: TObject);
    procedure buatDump(tabels:TstringList; filepath:string);
    procedure threadUpdateFinishAll(Sender: TObject);
    procedure threadUpdateExecute(Sender: TObject; Params: Pointer);
    procedure FormShow(Sender: TObject);
    procedure ResetSinkronisasi1Click(Sender: TObject);
    procedure threadBuatSyncExecute(Sender: TObject; Params: Pointer);
    procedure threadBuatSyncFinishAll(Sender: TObject);
  private
    { Private declarations }
    tpsFormActive : bool;
    procedure CreateMDIChild(const Name: string);
    procedure DisplayForm(namaForm:string;caption:string);
    procedure WmAfterShow(var Msg: TMessage); message WM_AFTER_SHOW;
  public
    { Public declarations }
    constructor Create(AOwner: TComponent; kode_login, username_login, role:string);overload;

  end;

var
  importberhasil:boolean;
  proses_berjalan: integer = 0;
  MainForm: TMainForm;
  MyWorkerThread: TMyWorkerThread;
  kode, username, dirsync, locfile:string;
  role_user:string;
  syncImport:SyncData;
implementation

{$R *.dfm}

uses CHILDWIN, about, TPS_Edit, Importer, View, excel_import, Proses_Data,
  U_Informasi, Login;

procedure TMyWorkerThread.Execute;
var I:integer;
begin
  //Here we do work
  //ShowMessage('start');
    number :=0;
    for I := 0 to 1000000000 do
    number:=number+1;
  //When we exit the procedure, the thread ends.
  //So we don't exit until we're done.
  //ShowMessage('finish');

end;

constructor TMainForm.Create(AOwner: TComponent; kode_login, username_login, role:string);
begin
  kode:=kode_login;
  username:=username_login;
  role_user:=role;
  inherited Create(AOwner);
end;

procedure TMainForm.BuatFileSinkronisasi1Click(Sender: TObject);
var sync:SyncData;
tanggalskrg:String;
begin
  tanggalskrg := FormatDateTime('dd-mm-yyyy_hhmmss', Now());
  locfile:='sync-'+username+'-'+tanggalskrg+'.kpu';

  if SelectDirectory('Select a directory', 'C:\, D:\, E:\', dirsync) then begin
    threadBuatSync.ThreadDialog:=threadDialogBuatSync;
    threadBuatSync.Execute(Self);
  end;
end;

procedure TMainForm.CreateMDIChild(const Name: string);
var
  Child: TMDIChild;
begin
  { create a new MDI child window }
  Child := TMDIChild.Create(Application);
  Child.Caption := Name;
  if FileExists(Name) then Child.Memo1.Lines.LoadFromFile(Name);
end;

procedure TMainForm.DataMaster1Click(Sender: TObject);
begin
  DisplayForm('data_master', 'Data Master Petugas');
end;

procedure TMainForm.DisplayForm(namaForm:string;caption:string);
var   importForm: TForm1;
      form:TForm;
      i:Integer;
begin
//showMessage(inttostr(proses_berjalan));
  i:=0;
  while i<MdiChildCount do
  begin
    if(MDIChildren[i].Name=namaForm)then
    begin
      i:=-1;
      break;
    end;
    i:=i+1;
  end;
  if(i<>-1) then
    begin
      if namaForm='Form1' then
          form:=TForm1.Create(Application)
      else if namaForm='tambahTps' then
        form:=TtambahTps.Create(Application)
      else if namaForm='editTps'  then
        form:=ttambah_orang.Create(Application)
        // form:=TeditTps.Create(Application)
      else if namaForm='Form2'  then
         form:=TForm2.Create(Application)
      else if namaForm='NewData'  then
         form:=TNewData.Create(Application)
      else if namaForm='excel'  then
         form:=texcel.Create(Application, kode)
      else if namaForm='Form_Data'  then
         form:=TForm_Data.Create(Application)
      else if namaForm='Form4'  then
         form:=TForm4.Create(Application, kode)
      else if namaForm='TPS_Print_Form'  then
         form:=TTPS_Print_Form.Create(Application, kode)
      else if namaForm='PPS_View_Form'  then
         form:=TPPS_View_Form.Create(Application, kode)
      else if namaForm='Rekap_Form'  then
         form:=TForm6.Create(Application)
      else if namaForm='DPT_Import'  then
         form:=Tdpt_import_form.Create(Application, kode)
      else if namaForm='viewDPT_Form'  then
         form:=TviewDPT_Form.Create(Application)
      else if namaForm='Form_NView'  then
        begin
          if proses_berjalan = 2 then
           form:=TForm_NView.Create(Application, kode, true, 2,username)
          else
           form:=TForm_NView.Create(Application, kode, false, 2,username);
        end
      else if namaForm='Form_ZView'  then
        begin
         if proses_berjalan = 8 then
           form:=TForm_NView.Create(Application, kode, true, 8,username)
          else
           form:=TForm_NView.Create(Application, kode, false, 8,username);
         end
      else if namaForm='frmInformasi'  then
         form:=TfrmInformasi.Create(Application, kode)
      else if namaForm='Form_XView'  then
        begin
         if proses_berjalan = 4 then
           form:=TForm_NView.Create(Application, kode, true, 4,username)
          else
           form:=TForm_NView.Create(Application, kode, false, 4,username);
         end
      else if namaForm='data_master'  then
         form:=TPPS_View_Form.Create(Application, kode)
      else if namaForm='Pengaturan'  then
         form:=TSetting_Form.Create(Application)
      else if namaForm='LogAct' then
         form:=TlogActivityForm.Create(Application, kode)
      else if namaForm='LogSync' then
         form:=TlogSyncForm.Create(Application, kode)
      else if namaForm='UserCrud' then
         form:=TcrudForm.Create(Application, username, kode)
      else if namaForm='BackupKec' then
        form:=TfBackupKec.Create(Application, kode);
      form.Caption := caption;
    end;
end;
procedure TMainForm.ToolButton1Click(Sender: TObject);
begin
//  ImportForm();
DisplayForm('Form1', 'Import Data');
end;

procedure TMainForm.ToolButton2Click(Sender: TObject);
begin
   //DisplayForm('Form2', 'View Data');
   DisplayForm('Form_NView', 'View Data');
end;

procedure TMainForm.ToolButton3Click(Sender: TObject);
begin
  DisplayForm('Rekap_Form', 'Rekap Keseluruhan');
end;

procedure TMainForm.toolClick(Sender: TObject);
begin
DisplayForm('TPS_Print_Form', 'Print/Export Data Pemilih');

end;

procedure TMainForm.pps_formClick(Sender: TObject);
begin
  DisplayForm('PPS_Form', 'PPS' );

end;

procedure TMainForm.printtps(Sender: TObject);
begin
//   EditTPSForm();
DisplayForm('editTps', 'Edit TPS');
end;

procedure TMainForm.ToolButton4Click(Sender: TObject);
begin
    DisplayForm('NewData', 'New Data');
end;

procedure TMainForm.ToolButton5Click(Sender: TObject);
var i: integer;
begin
for i:= 0 to MdiChildCount - 1 do
  MDIChildren[i].Close;
end;

procedure TMainForm.ToolButton6Click(Sender: TObject);
begin
  //Showmessage(ses);
  DisplayForm('excel', 'Import Excel DP4');
end;

procedure TMainForm.ToolButton7Click(Sender: TObject);
begin
   DisplayForm('Form4', 'Manajemen TPS');
end;

procedure TMainForm.ToolButtonzClick(Sender: TObject);
begin
   DisplayForm('PPS_View_Form', 'Form Daftar Petugas');

end;

procedure TMainForm.ToolPrintClick(Sender: TObject);
begin
DisplayForm('TPS_Print_Form', 'Print TPS');

end;


procedure TMainForm.ExcelImportExecute(Sender: TObject);
begin
DisplayForm('excel', 'Import Excel Data');
//DisplayForm('tambahTps', 'Form Tambah TPS');
//  TambahTPSForm();
end;

procedure TMainForm.FileOpen1Execute(Sender: TObject);
begin
//  if OpenDialog.Execute then
//    CreateMDIChild(OpenDialog.FileName);
DisplayForm('Form1', 'Import Data');
end;

procedure TMainForm.FormPrintTPS(Sender: TObject);
begin
  DisplayForm('TPS_Print_Form', 'Print TPS');
end;


procedure TMainForm.ImportDPTTerakhir1Click(Sender: TObject);
begin
  DisplayForm('DPT_Import', 'Import DPT');
end;

procedure TMainForm.ImportFileSinkronisasi1Click(Sender: TObject);
var
  openDialog : TOpenDialog;    // Open dialog variable
  sync:SyncData;
begin
  // Create the open dialog object - assign to our open dialog variable
  openDialog := TOpenDialog.Create(self);
  // Set up the starting directory to be the current one
  openDialog.InitialDir := GetCurrentDir;
  // Only allow existing files to be selected
  openDialog.Options := [ofFileMustExist];
  // Allow only .dpr and .pas files to be selected
  openDialog.Filter := 'KPU sync files|*.kpu';
   // 'Delphi project files|*.dpr|Delphi pascal files|*.pas';

  // Select pascal files as the starting filter type
  //openDialog.FilterIndex := 2;

  // Display the open file dialog
  if openDialog.Execute
  then
  begin
    syncImport:=SyncData.Create(openDialog.FileName, kode, username);
//    importberhasil:= syncImport.readate;
    JvThread2.ThreadDialog:=JvThreadSimpleDialog2;
    JvThread2.Execute(self);

  end;

  // Free up the dialog
  openDialog.Free;
end;

procedure TMainForm.ViewDataPemilihClick(Sender: TObject);
begin
  DisplayForm('Form_NView', 'Pemutakhiran Daftar Pemilih Tahap DPS');
end;

procedure TMainForm.ViewDataPemilihTambClick(Sender: TObject);
begin
  DisplayForm('Form_ZView', 'Pemutakhiran Daftar Pemilih Tahap DPTambahan');
end;

procedure TMainForm.ViewDPTPemutakhirClick(Sender: TObject);
begin
  DisplayForm('Form_XView', 'Pemitakhiran Daftar Pemilih Tahap DPT');
end;

procedure TMainForm.ViewDPTTerakhir1Click(Sender: TObject);
begin
  DisplayForm('viewDPT_Form', 'View DPT');
end;

procedure TMainForm.ViewTPSClick(Sender: TObject);
begin
DisplayForm('Form4', 'Manajemen TPS');
end;

procedure TMainForm.Fo1Click(Sender: TObject);
begin
//  DisplayForm('Form_Data', 'Form Data Ganda');

end;

procedure TMainForm.FormCreate(Sender: TObject);
var extfile:ExternalFile;
    setting:TSetting_Form;
    query, nama_proses, akhir_proses:String;
    id_proses:Integer;
    tgl: string;
begin
  extfile:=ExternalFile.Create;
  setting:=TSetting_Form.Create;

  //if MyWorkerThread<>nil then
  //  raise Exception.Create('One thread have already been started!');
  //MyWorkerThread := TMyWorkerThread.Create(false);

  setting:=TSetting_Form.Create;
  ZConnection1.HostName:=setting.host;
  ZConnection1.Protocol:=setting.protocol;
  ZConnection1.Database:=setting.database;
  ZConnection1.User:=setting.user;
  ZConnection1.Password:=setting.password;
  ZConnection1.Connected:=true;
  zquery1.Connection:=ZConnection1;
  qryCek.Connection:=ZConnection1;
  qryTabel.Connection:=ZConnection1;

  zquery1.active:=false;
  tgl := formatDateTime('yyyy-mm-dd', Date);

  query:= 'SELECT a.PROSES, a.TANGGAL_SELESAI, b.KETERANGAN FROM proses_berjalan a INNER JOIN info_tanggal b ON a.ID_INFO = b.ID WHERE a.TANGGAL_MULAI <= '+quotedStr(tgl)+' AND a.TANGGAL_SELESAI >= '+quotedStr(tgl)+'';
  ZQuery1.SQL.Clear;
  ZQuery1.SQL.Text := query;
  zquery1.active:=true;
  zquery1.first;
  if(zquery1.RecordCount>0)then begin
    while (not ZQuery1.Eof) do begin
      id_proses := ZQuery1.Fields[0].AsInteger;
      proses_berjalan := proses_berjalan+id_proses;
      case id_proses of
        1 :
          begin
            nama_proses := 'DP4';
            File1.Enabled:=true;
          end;
        2, 5 :
          begin
            nama_proses := 'Penyusunan DPS';
            //Window1.Enabled:=true;
            PenyusunanDPS1.Enabled:=True;
          end;
        3, 6 :
          begin
            nama_proses := 'Penyusunan DPTambahan';
            Help1.Enabled:=true;
            //Window1.Enabled:=true;
            PenyusunanDPS1.Enabled:=True;
          end;
        4, 7 :
          begin
            nama_proses := 'Penyusunan DPT';
            PenyusunandanPerbaikanDPT1.Enabled:=true;
          end;
        99 :
          begin
            nama_proses := 'Selesai';
            PenyusunandanPerbaikanDPT1.Enabled:=true;
            Help1.Enabled:=true;
            //Window1.Enabled:=true;
            PenyusunanDPS1.Enabled:=True;
          end;
      end;
//      showMessage(nama_proses);
      ProsesLabel.Caption := ProsesLabel.Caption + ' ' + nama_proses;
      zquery1.Next;
    end;
  end;
  if(role_user = '0') then
  begin
    File1.Visible:=false;
    Pengaturan1.Items[2].Visible:=false;
    Pengaturan1.Items[3].Visible:=false;
    //Pengaturan1.Find('BasisData1').Visible:=false;
    //Pengaturan1.Find('User1').Visible:=false;
  end;
  if(Length(kode)>2)then // petugas kecamatan
  begin
    estDump1.Visible:=false;
    LogAktivitasSinkronisasi1.Visible:=false;
    ImportFileSinkronisasi1.Visible:=false;
    pengaturan1.items[3].visible:=false;
  end;
  if(kode = '00') then begin// petugas pr0vinsi
    estDump1.Visible:=false;
    BuatFileSinkronisasi1.Visible := false;
  end;

  if(Date < EncodeDate( 2012, 10, 10 )) then
  begin
//    showMessage('tutup');
     pengaturan1.Visible := false;
  end;

  if(Date > EncodeDate( 2013, 2, 25 )) then
  begin
//    showMessage('tutup');
     pengaturan1.Visible := false;
  end;
 end;

procedure TMainForm.FormPetugas1Click(Sender: TObject);
begin
  DisplayForm('PPS_View_Form', 'Form Petugas' );
end;

procedure TMainForm.TambahDataPemilihClick(Sender: TObject);
begin
  //AboutBox.ShowModal;
    DisplayForm('NewData', 'Form Tambah Data Pemilih');
end;

procedure TMainForm.FileCloseItemClick(Sender: TObject);
begin
  //DisplayForm('Form_Data', 'Form Data Ganda');
  ShellExecute(
  Application.Handle,
  'open',
  'Exclude.exe',
  nil,
  nil,
  SW_SHOWNORMAL
);
end;

procedure TMainForm.FileExit1Execute(Sender: TObject);
begin
  Close;
end;

procedure TMainForm.menuInformasi1Click(Sender: TObject);
begin
    DisplayForm('frmInformasi', 'Form Informasi');
end;

procedure TMainForm.EksportPrintFormkPU1Click(Sender: TObject);
begin
  DisplayForm('TPS_Print_Form', 'Print Form KPU');
end;

procedure TMainForm.LogoutClick(Sender: TObject);
var
  sExeName:String;
  loginform:TLoginForm;
begin
  Close;

//  loginform :=TLoginForm.Create(Self);
//  loginform.ShowModal;
//  loginform.Free;
//  mainform.Hide;
  //sExeName := ExtractFileName(Application.ExeName);
//        CloseModal;
//        Hide;

  {
 ShellExecute(
    Application.Handle,
    'open',
    PChar(sExeName),
    nil,
    nil,
    SW_SHOWNORMAL
  );}
end;

procedure TMainForm.Pengaturan1Click(Sender: TObject);
begin
  DisplayForm('Pengaturan', 'Form Pengaturan Koneksi');
end;

procedure TMainForm.LogAktivitas1Click(Sender: TObject);
begin
  DisplayForm('LogAct', 'Log Aktivitas');
end;

procedure TMainForm.LogAktivitasSinkronisasi1Click(Sender: TObject);
begin
  DisplayForm('LogSync', 'Log Aktivitas');
end;

procedure TMainForm.User1Click(Sender: TObject);
begin
  DisplayForm('UserCrud', 'Pengaturan User');
end;

procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
var
  sExeName:string;
  sel:integer;
begin
  sel:= messagedlg('Apakah Anda yakin ingin logout?',mtConfirmation,mbOKCancel, 0);
  if(sel = mrOK) then begin
  sExeName := ExtractFileName(Application.ExeName);
        //CloseModal;
        //Hide;


 ShellExecute(
    Application.Handle,
    'open',
    PChar(sExeName),
    nil,
    nil,
    SW_SHOWNORMAL
  );
end
  else
    abort;
end;

procedure TMainForm.JvThread2Execute(Sender: TObject; Params: Pointer);
begin
  importberhasil:= syncImport.readate;
end;

procedure TMainForm.JvThread2FinishAll(Sender: TObject);
begin
  if(importberhasil) then
    ShowMessage('Sinkronisasi telah dilakukan')
  else
    showMessage('file sudah pernah dimasukkan, sinkronisasi gagal');
  syncImport.Free;
end;

procedure TMainForm.BackupDatabase1Click(Sender: TObject);
var
  syncDump : syncData;
begin
  syncDump := SyncData.Create(openDialog.FileName, kode, username);
  syncDump.writeDump;
  //
end;

procedure TMainForm.RestoreDatabase1Click(Sender: TObject);
var
  namafile, peringatan: string;
  syncDump : syncData;
  buttonSelected : integer;
begin
  //open file
  //syncDump := SyncData.Create(openDialog.FileName, kode, username);
  openDialog.Filter := 'MySQL dump |*.sql';
  if openDialog.Execute then begin
    //kasih peringatan
    peringatan := 'Dengan me-restore backup database, database yang ada sekarang akan hilang! Apakah Anda yakin?';
    buttonSelected := MessageDlg(peringatan,mtWarning , mbOKCancel, 0);
    if(buttonSelected = mrOK) then begin
      namafile := openDialog.FileName;
      syncDump.restoreDump(namafile);
    end;
  end;
end;

procedure TMainForm.estDump1Click(Sender: TObject);
var
  tabels:TStringList;
  filePath:String;
begin
  //
  DisplayForm('BackupKec', 'Backup per Kecamatan');  
end;

procedure TMainForm.buatDump(tabels:TstringList; filepath:string);
var
  desFile:TextFile;
  curtable:string;
  table_num, idx, count, col_num, idx_col, row_num:integer;
  sql_cek, sql_sel, str_added, value:string;
begin
  table_num := tabels.Count;
  for idx:=0 to table_num-1 do begin
    curtable:=tabels[idx];
    //cek tabelnya ada atau engga
    sql_cek := 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '+quotedStr(ZConnection1.Database)+' AND TABLE_NAME = '+quotedStr(curtable);
    qryCek.Active:=false;
    qryCek.SQL.Clear;
    qryCek.SQL.Text:=sql_cek;
    qryCek.Active:=true;
    if qryCek.RecordCount >= 1 then begin
      //tabel ada
      //buka file
      AssignFile(desFile, filepath);
      if FileExists(filepath) then
        Append(desFile)
      else
        Rewrite(desFile);

      //drop if exists
      str_added := 'DROP TABLE IF EXISTS '+curtable+';'+sLineBreak;
      WriteLn(desFile, str_added);

      //show create table
      sql_sel := 'SHOW CREATE TABLE '+curtable;
      ZQuery1.Active:=false;
      ZQuery1.SQL.Clear;
      ZQuery1.SQL.Text:=sql_sel;
      ZQuery1.Active:=True;
      ZQuery1.First;
      str_added:=ZQuery1.Fields[1].AsString+sLineBreak;
      WriteLn(desFile, str_added);

      //isi
      str_added:='';
      sql_sel := 'SELECT * FROM '+curtable;
      ZQuery1.Active:=false;
      ZQuery1.SQL.Clear;
      ZQuery1.SQL.Text:=sql_sel;
      ZQuery1.Active:=True;
      ZQuery1.First;
      col_num := ZQuery1.FieldCount;
      row_num := ZQuery1.RecordCount;
      count:=0;
      while(not ZQuery1.Eof) do begin
        if ((count mod 500) = 0) then begin
          str_added:=str_added+'INSERT INTO '+curtable+' VALUES';
        end;
        str_added:=str_added+'(';
        for idx_col := 0 to col_num-1 do begin
          value :=ZQuery1.Fields[idx_col].AsString;
          value := StringReplace(value, '"', ' ',[rfReplaceAll, rfIgnoreCase]);
          value := StringReplace(value, '\', ' ',[rfReplaceAll, rfIgnoreCase]);
          str_added:=str_added+'"'+value+'"';
          if idx_col < (col_num-1) then str_added:=str_added+',';
        end;
        if (((count mod 500) = 499) or (count = (row_num-1))) then
          str_added:=str_added+');'+sLineBreak
        else
          str_added:=str_added+'), ';
        count:=count+1;
        ZQuery1.Next;
      end;
      WriteLn(desFile, str_added);

      CloseFile(desFile);
    end;
  end;
end;

procedure TMainForm.threadUpdateFinishAll(Sender: TObject);
begin
  //
end;

procedure TMainForm.threadUpdateExecute(Sender: TObject; Params: Pointer);
var
  query:string;
  curtable, curtps, curid, nexttps:string;

begin
    //buat tabel biar ga ngulang lagi
    query := 'CREATE TABLE  fixme (dummy INT NULL) ENGINE = MyISAM';
    ZQuery1.Active:=false;
    ZQuery1.SQL.Clear;
    ZQuery1.SQL.Text := query;
    zquery1.ExecSQL;

    //cari tabel pemilih
    query := 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '+quotedStr('pemilih_%')+' AND TABLE_NAME <> '+quotedStr('pemilih_ganda')+' AND TABLE_SCHEMA = '+quotedStr(ZConnection1.Database);
    qryTabel.active:=false;
    qryTabel.SQL.Clear;
    qryTabel.SQL.Text:=query;
    qryTabel.Active:=true;
    qryTabel.First;
    while(not qryTabel.Eof) do begin

      curtable := qryTabel.fieldByName('TABLE_NAME').AsString;
      query:= 'UPDATE '+curtable+' SET STATUS1 = ''0'' WHERE STATUS1 = ''2''';
      ZQuery1.Active:=false;
      ZQuery1.SQL.Clear;
      ZQuery1.SQL.Text := query;
      zquery1.ExecSQL;

      query:= 'UPDATE '+curtable+' SET CACAT = ''0'' WHERE CACAT = ''6''';
      ZQuery1.Active:=false;
      ZQuery1.SQL.Clear;
      ZQuery1.SQL.Text := query;
      zquery1.ExecSQL;

      //jika usernya kecamatan

      if(length(kode) > 2) then begin
        //update id tps, pokoknya pemilih id tpsnya harus di masing-masing keldes
        query:= 'SELECT a.ID_USER, a.TPS, b.NAMA FROM '+curtable+' a INNER JOIN daftar_tps b ON a.TPS = b.ID_TPS WHERE b.KODE_DESA <> '+quotedStr(copy(curtable,9,8));
        ZQuery1.Active:=false;
        ZQuery1.SQL.Clear;
        ZQuery1.SQL.Text := query;
        zquery1.active:=true;
        zquery1.First;
        memo1.Text:=memo1.Text+' '+inttostr(zquery1.RecordCount);
        while (not zquery1.Eof) do begin
          curtps:=zquery1.Fields[2].AsString;
          curid:=zquery1.Fields[0].AsString;
          //cari tps dengan nama sama di desa nya
          query:= 'SELECT ID_TPS FROM daftar_tps WHERE NAMA = '+quotedstr(curtps)+' AND KODE_DESA = '+quotedStr(copy(curtable,9,8));
          qryCek.Active:=false;
          qryCek.SQL.Clear;
          qryCek.SQL.Text:=query;
          qryCek.Active:=true;
          qryCek.First;

          if qryCek.RecordCount > 0 then
            nexttps := qryCek.Fields[0].AsString
          else
            nexttps := '0';

          query := 'UPDATE '+curtable+' SET TPS = '+quotedStr(nexttps)+' WHERE ID_USER = '+quotedstr(curid);

          memo1.Text:=memo1.Text+' '+curtps+' '+query;
          qryCek.Active:=false;
          qryCek.SQL.Clear;
          qryCek.SQL.Text:=query;
          qryCek.ExecSQL;
          zquery1.Next;
        end;
      end;
      memo1.Text:=memo1.Text+' - '+copy(curtable,9,8)+sLineBreak;
      qryTabel.Next;
    end;
end;

procedure TMainForm.WmAfterShow(var Msg: TMessage);
var
  query:string;
begin
  //ngecek tabel 'fixme' udah ada belom
  query := 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '+quotedStr('fixme')+' AND TABLE_SCHEMA = '+quotedStr(ZConnection1.Database);
  qryCek.active:=false;
  qryCek.SQL.Clear;
  qryCek.SQL.Text:=query;
  qryCek.Active:=true;
  qryCek.First;
  if(qryCek.RecordCount = 0) then begin
    threadUpdate.ThreadDialog := threadDialogUpdate;
    threadUpdate.Execute(self);
  end;  
  //ShowMessage('WM_AFTER_SHOW received!');
end;

procedure TMainForm.FormShow(Sender: TObject);
begin
  PostMessage(Self.Handle, WM_AFTER_SHOW, 0, 0);
end;

procedure TMainForm.ResetSinkronisasi1Click(Sender: TObject);
begin
  with zquery1 do begin
    active:=false;
    sql.Clear;
    sql.Text:= 'TRUNCATE history_sinkronisasi';
    execsql;
  end;

  showmessage('Sinkronisasi berhasil di-reset');
end;

procedure TMainForm.threadBuatSyncExecute(Sender: TObject;
  Params: Pointer);
var
  sync:syncData;
begin
  sync:=SyncData.Create(locfile,kode, username);
  sync.writeDate(dirsync);
end;

procedure TMainForm.threadBuatSyncFinishAll(Sender: TObject);
begin
  Showmessage('Sinkronisasi Berhasil Dilakukan, pada file '+locfile);
  ShellExecute(Application.Handle,
    PChar('explore'),
    PChar(dirsync),
    nil,
    nil,
    SW_SHOWNORMAL);
end;

end.
